<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import myClass from '@/assets/js/common'
import store from "@/store/store";
import { Indicator } from "mint-ui";
import sha1 from 'js-sha1'
export default {
  name: "app",
  data() {
    return {
      Url:
        "http://mall.eshangtech.com:8010/MobileServicePlatform/Handler/handler_ajax.ashx?",
      openid: "",
      wxid: ""
    };
  },
  watch: {
    $route (to, from) {
        this.$store.commit('mutateChangeZIndex',{overHidden: false, zIndex: 10})
    }
  },
  methods: {
    // 截取地址参数
    // WechatGetQueryString(name) {
    //   let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),   
    //     r = window.location.search.substr(1).match(reg);
    //   if (r !== null) return unescape(r[2]);
    //   return null;
    // },
    // 微信登录
    WechatLogin() {
      //let code = this.WechatGetQueryString("code");
      let code = this.$route.query['code'] || myClass.getQueryString('code')
      // let code = myClass.getQueryString('code')
      // alert(window.location.href)
      if (code === undefined) {
        let urls = window.location.href;
        let state = urls.slice(urls.indexOf('?')+1)
        let Url = urls.slice(0,urls.indexOf('?'))
        window.location.href =
          "http://eshangtech.com/wxpush.html?appid=wxcf4dbe1815d5d872&scope=snsapi_userinfo&state=&redirect_uri="+escape(urls)

        // window.location.href =
        //   "http://eshangtech.com/wxpush.html?appid=wxcf4dbe1815d5d872&scope=snsapi_userinfo&state="+
        //     escape(state)+
        //   "&redirect_uri="+escape(Url);
      } else {
        this.$http
          .get(
            "http://mall.eshangtech.com:8010/MobileServicePlatform/Handler/handler_ajax.ashx?action_type=GetWechatInfo&RegisterType=3&action_data="+code
          )
          .then(response => {
            // alert(JSON.stringify(response))
            // success callback
            this.GetJsapi_Ticket() //发票验证
            this.openid = response.data.WechatInfoObject[0].WECHAT_OPENID;
            // this.openid = 'oLBr30oH1UhVQRcj2XIMxtSlIxQE'
            this.wxid = response.data.WechatInfoObject[0].RTWECHATPUSH_ID;
            if (this.openid != "") {
              this.setCookie("openid", this.openid, 365);
              // this.setCookie("openid", 'oLBr30oH1UhVQRcj2XIMxtSlIxQE', 365);
              this.setCookie("wxid", this.wxid, 365);
              store.commit("getOpenid", this.openid); // openid存入store,全局调用
              // store.commit("getOpenid", 'oLBr30oH1UhVQRcj2XIMxtSlIxQE');
              store.commit("getWxid", this.wxid); // wxid存入store,全局调用
            }
            this.Member(); // 会员验证
            // console.log(response);
          })
          .catch(error => {
            // console.log(error);
          });
      }
    },
    // 会员验证
    Member: function() {
      setTimeout(()=>{
        Indicator.close();
      },1500)
      Indicator.close(); // 关闭初始动画
      this.$http
        .get(
          this.Url +
            "action_type=GetMembershipInfo&action_record=" +
            store.state.openid +
            "&RegisterType=Check&WECHATPUBLICSIGN_ID=3"
        )
        .then(response => {
          // alert(JSON.stringify(response))
          // success callback
          if (response.data.MEMBERSHIP.length == 0) {
            this.$router.push({ path: "/register" }); //进入注册界面
          } else {
            this.setCookie("useName", response.data.MEMBERSHIP[0].MEMBERSHIP_NAME, 365); //存储默认用户名-cookie
            store.commit("getuseName", response.data.MEMBERSHIP[0].MEMBERSHIP_NAME); //存储默认用户名-store
            this.$http
              .get(
                this.Url +
                  "action_type=GetModuleAuthority&action_data=" +
                  store.state.openid +
                  "&action_record=4ef21b1f-aada-49b7-9538-24df20dee1c7"
              )
              .then(response => {
                // success callback
                // console.log('Member',response)
                if (response.data.ModuleAuthorityObject.length == 0) {
                  this.$http
                    .get(
                      this.Url +
                        "action_type=GetModuleAuthority&action_data=" +
                        store.state.openid +
                        "&action_record=994cca48-52a8-4164-bea1-7680fd65a400"
                    )
                    .then(response => {
                      // success callback
                      if (response.data.ModuleAuthorityObject.length == 0) {
                        if (store.state.HbusinessType == "0") {
                          // console.log('tz',store.state.openid)
                          this.$router.push({ path: "/Homepage/" }); //进入默认界面
                        } else if (store.state.HbusinessType == "1") {
                          this.$router.push({ path: "/Homepage/page1" }); //进入通知提醒界面
                        } else if (store.state.HbusinessType == "2") {
                          this.$router.push({ path: "/Homepage/page3" }); //进入权限审批界面
                        } else if (store.state.HbusinessType == "3") {
                          this.$router.push({ path: "/Homepage/page4" }); //进入数据校验界面
                        }else if (store.state.HbusinessType == "4") {
                          this.$router.push({ path: "/Homepage/expenses" }); //进入财务报销界面
                        }
                      } else {
                        if (store.state.HbusinessType == "0") {
                          this.$router.push({ path: "/Homepage/HelloWorld" }); //进入业务审批界面
                        } else if (store.state.HbusinessType == "1") {
                          this.$router.push({ path: "/Homepage/page1" }); //进入通知提醒界面
                        } else if (store.state.HbusinessType == "2") {
                          this.$router.push({ path: "/Homepage/page3" }); //进入权限审批界面
                        } else if (store.state.HbusinessType == "3") {
                          this.$router.push({ path: "/Homepage/page4" }); //进入数据校验界面
                        }else if (store.state.HbusinessType == "4") {
                          this.$router.push({ path: "/Homepage/expenses" }); //进入财务报销界面
                        }
                      }
                    })
                    .catch(error => {
                      // console.log(error);
                    });
                } else {
                  if (store.state.HbusinessType == "0") {
                    this.$router.push({ path: "/Homepage/HelloWorld" }); //进入业务审批界面
                  } else if (store.state.HbusinessType == "1") {
                    this.$router.push({ path: "/Homepage/page1" }); //进入通知提醒界面
                  } else if (store.state.HbusinessType == "2") {
                    this.$router.push({ path: "/Homepage/page3" }); //进入权限审批界面
                  } else if (store.state.HbusinessType == "3") {
                    this.$router.push({ path: "/Homepage/page4" }); //进入数据校验界面
                  }else if (store.state.HbusinessType == "4") {
                    this.$router.push({ path: "/Homepage/expenses" }); //进入财务报销界面
                  }
                }
              })
              .catch(error => {
                // console.log(error);
              });
          }
        })
        .catch(error => {
          // console.log(error);
        });
    },
    // 设置cookie
    setCookie: function(cname, cvalue, exdays) {
      var d = new Date();
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
      var expires = "expires=" + d.toUTCString();
      // console.log(cname + "=" + cvalue + "; " + expires);
      document.cookie = cname + "=" + cvalue + "; " + expires;
      // console.log(document.cookie);
    },
    // 获取cookie
    getCookie: function(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(";");
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
      }
      return "";
    },
    // 清除cookie
    clearCookie: function(cname) {
      this.setCookie(cname, "", -1);
    },
    // 地址信息
    checkCookie: function() {
      // 截取地址参数信息
      let ProinstState = myClass.getQueryString("ProinstState") || '';
      let STATISTICS_DATE = myClass.getQueryString("STATISTICS_DATE") || '';
      let HIGHWAYPROINST_ID = myClass.getQueryString("HIGHWAYPROINST_ID") || '';
      let HIGHWAYPROINST_TYPE = myClass.getQueryString("HIGHWAYPROINST_TYPE") || '';
      let POWERAPPLY = myClass.getQueryString("POWERAPPLY") || '';
      let Serverpart_ID = myClass.getQueryString("Serverpart_ID") || '';
      let FINANCEPROINST_ID = myClass.getQueryString("FINANCEPROINST_ID") || ''; //业务内码
      // 设置地址参数cookie
      // this.setCookie("openid", 'oLBr30oH1UhVQRcj2XIMxtSlIxQE', 365);
      // store.commit("getOpenid", 'oLBr30oH1UhVQRcj2XIMxtSlIxQE');
      // this.setCookie("openid", 'oLBr30gPoJjajBxACDe3veXBlzrQ', 365);
      // store.commit("getOpenid", 'oLBr30gPoJjajBxACDe3veXBlzrQ');
      if (ProinstState != null) {
        this.setCookie("ywtype", ProinstState, 365);
        this.setCookie("date", STATISTICS_DATE, 365);
        this.setCookie("ywId", HIGHWAYPROINST_ID, 365);
        this.setCookie("tztype", HIGHWAYPROINST_TYPE, 365);
        this.setCookie("qxywId", POWERAPPLY, 365);
        this.setCookie("fwqId", Serverpart_ID, 365);
        this.setCookie("finId", FINANCEPROINST_ID, 365);//业务内码
      }
      // 获取地址参数cookie
      let openid = this.getCookie("openid");
      let wxid = this.getCookie("wxid");
      let HbusinessType = this.getCookie("ywtype");
      let date = this.getCookie("date");
      let HbusinessId = this.getCookie("ywId");
      let HtzType = this.getCookie("tztype");
      let HqxId = this.getCookie("qxywId");
      let fwqId = this.getCookie("fwqId");
      let finId = this.getCookie("finId");//业务内码
      // 存入store,全局调用
      store.commit("getOpenid", openid); // openid存入store,全局调用
      store.commit("getWxid", wxid); // wxid存入store,全局调用
      store.commit("getHbusinessType", HbusinessType);
      store.commit("getdate", date);
      store.commit("getHbusinessId", HbusinessId);
      store.commit("getHtzType", HtzType);
      store.commit("getHqxId", HqxId);
      store.commit("getfwqId", fwqId);
      store.commit("getfinId",finId);//业务内码
    },
    GetJsapi_Ticket(){
      this.$api.get('http://mall.eshangtech.com:8010/MobileServicePlatform/Handler/handler_ajax.ashx', '', {
      action_type: 'GetAccessToken',
      AppSecret: 'ba17c52167b086542256f2f6f40ffb1f',
      AppID: 'wxcf4dbe1815d5d872'})
      .then((res) => {
        // alert(JSON.stringify(res.data))
        if (res && res.data) {
          let result = res.data
          this.$api.get('http://mall.eshangtech.com:8010/MobileServicePlatform/Handler/handler_ajax.ashx', '', {
            action_type: 'GetJsapi_Ticket',
            action_data: result})
            .then((res) => {
              // alert(JSON.stringify(res.data))
              if (res && res.data && res.data.ticket) {
                let jsapi_ticket = res.data.ticket // 
                let nonceStrs = Math.random().toString(36).substr(2, 15) // 随机字符串
                let timestampStrs = Date.parse(new Date()).toString().substring(0, 10) // 时间戳
                let urlStrs =window.location.href.split('#')[0] // 当前地址
                let string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStrs + "&timestamp=" + timestampStrs + "&url=" + urlStrs // 字符串拼接
                let signatureStrs = sha1(string1) // sha1签名
                this.$wx.config({
						// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                debug: false,
                // 必填，公众号的唯一标识
                appId: 'wxcf4dbe1815d5d872',
                // 必填，生成签名的时间戳
                timestamp: timestampStrs,
                // 必填，生成签名的随机串
                nonceStr: nonceStrs,
                // 必填，签名，见附录1
                signature: signatureStrs,
                // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                jsApiList: ['checkJsApi', 'scanQRCode']
              })
                this.$wx.error(function(res) {
                  alert("出错了：" + res.errMsg); //这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
                })
                this.$wx.checkJsApi({
                  jsApiList: ['scanQRCode'],
                  success: function(res) {}
                })
              }
            })
          }
        })
    }
  }, 
  created() {
    
    this.setCookie("openFrom", false, 365); // 财务报销列表
    Indicator.open(); // 打开初始动画
    // if(this.getCookie("openid") !== undefined 
    // && this.getCookie("openid") !== ""
    // && this.getCookie("wxid") !== undefined
    // && this.getCookie("wxid") !== ""){
    //   store.commit("getOpenid", this.getCookie("openid")); // openid存入store,全局调用
    //   store.commit("getWxid", this.getCookie("wxid")); // wxid存入store,全局调用
      this.Member(); //会员验证
      // Indicator.close();   
    // }else{
      // this.WechatLogin(); // 微信登录
    // }
    // this.checkCookie(); // 地址信息 
    this.$router.push({ path: "/Homepage" }); //进入主界面
  }
};
</script>

<style lang="stylus">
.picker-alert
  background #fff
  text-align center
  position fixed
  left 0
  right 0
  bottom 0
  z-index 2007
  .picker-toolbar
    display flex
    justify-content space-between
    padding 0.5rem
</style>
